<?php

namespace app\admin\controller\cms;

use addons\qrcode\library\Service;
use app\common\controller\Backend;
use OSS\OssClient;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Response;
use youdao\Youdao;

/**
 * 发货记录
 *
 * @icon fa fa-circle-o
 */
class Delivery extends Backend
{

    /**
     * Delivery模型对象
     * @var \app\common\model\cms\Delivery
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\cms\Delivery;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $province_info = \app\common\model\cms\Area::where('id',$row->user->province)->value('name');
                $city_info = \app\common\model\cms\Area::where('id',$row->user->city)->value('name') ?? '';
                $district_info = \app\common\model\cms\Area::where('id',$row->user->district)->value('name')  ?? '';
                if ($province_info && $city_info && $district_info){
                    $row->user->address = $province_info.'-'.$city_info.'-'.$district_info.' '.$row->user->address;
                }
//                $row->getRelation('user')->visible(['username','nickname','avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $qrcode = $this->getQrcode();
            $params['qrcode_str'] = $qrcode['qrcode_str'];
            $params['qrcode'] = $qrcode['qrcode'];

            if (!$params['qrcode'] || !$params['qrcode_str']){
                $this->error('二维码生成失败');
            }
            $result = $this->model->allowField(true)->save($params);
            //标签
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    private function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        if ($this->model->where('qrcode_str', $randomString)->find()){
            return $this->generateRandomString($length);
        }
        return $randomString;
    }

    public function getQrcode()
    {
        $config = get_addon_config('qrcode');

        $data = [
            'code' => $this->generateRandomString(11),
            'type' => 'delivery',
        ];

        $http_build_query_data = http_build_query($data);
        $qrCode = Service::qrcode([
            'text' => $http_build_query_data
        ]);
        // 直接显示二维码
        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';
        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码

        $response->content($qrCode->writeString());

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        $qrcode_path = '';
        if (is_really_writable($qrcodePath)) {
            $fileName = md5(implode('', ['text' => $http_build_query_data])). '.'. $config['format'];
            $aly_oss_config = get_addon_config('alioss');
            $filePath = $qrcodePath . $fileName;
            $qrCode->writeFile($filePath);

            try {
                $alioss = new OssClient($aly_oss_config['accessKeyId'], $aly_oss_config['accessKeySecret'], $aly_oss_config['endpoint']);
                $res = $alioss->uploadFile($aly_oss_config['bucket'],$fileName,$filePath);
                $qrcode_path = $res['info']['url'];
                return [
                    'qrcode_str' => $data['code'],
                    'qrcode' => $qrcode_path
                ];
            } catch (\Exception $e) {
                return [
                    'qrcode_str' => '',
                    'qrcode' => ''
                ];
            }
        }
    }
}
